//
//  WBHomeTableViewController.swift
//  weibo
//
//  Created by  郭航 on 16/6/23.
//  Copyright © 2016年 郭航. All rights reserved.
//

import UIKit

private let cellID = "cell"

class WBHomeTableViewController: WBBasicTableViewController {
    
    var dataArray: [WBFristPageDataModel] = [WBFristPageDataModel]()
    
    private lazy var refreshView: GHRefresh = GHRefresh()
    
    private lazy var ActIndicator: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        view.color = APPTintColor
        
        return view
    }()
    
    /// 提示标签
    private lazy var promptLabel: UILabel = {
        let label = UILabel(textColor: UIColor.whiteColor(), textAlignment: .Center, font: 13)
        
        label.backgroundColor = APPTintColor
        label.frame = CGRect(x: 0, y: 64 - 34, width: SCREENW, height: 34)
        label.alpha = 0
        
        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
       
        if !(WBUserInfor.shareWBUserInfor.isLogin) {
            let basicView = view as! WBBasicView
            basicView.setIconImageAddMessage(nil, message: nil)
            return
        }
        
        tableView.registerClass(WBFristPageTableViewCell.self, forCellReuseIdentifier: cellID)
        
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200
        
        tableView.separatorStyle = .None
        
        tableView.addSubview(refreshView)
        
        refreshView.addTarget(self, action: #selector(WBHomeTableViewController.refreshViewValueChanged), forControlEvents: .ValueChanged)
        
        tableView.tableFooterView = ActIndicator
        
        loadData(pullUp: ActIndicator.isAnimating())
    }
    
    @objc private func refreshViewValueChanged() -> Void {
        loadData(pullUp: false)
    }
    
    private func showPromptLabel(count: Int) -> Void {
        if promptLabel.superview == nil {
            navigationController?.view.insertSubview(promptLabel, belowSubview: (navigationController?.navigationBar)!)
        }
        
        if count > 0 {
            promptLabel.text = "更新了\(count)条微博"
        } else {
            promptLabel.text = "已经是最新的了"
        }
        
        UIView.animateWithDuration(0.25, animations: {
            self.promptLabel.alpha = 1
            self.promptLabel.transform = CGAffineTransformMakeTranslation(0, 34)
            }) { (_) in
                UIView.animateWithDuration(0.25, delay: 2, options: [], animations: { 
                    self.promptLabel.alpha = 0
                    self.promptLabel.transform = CGAffineTransformIdentity
                    }, completion: nil)
        }
    }
    
    func loadData(pullUp pullUp: Bool) -> Void {
        var since_id: Int64 = 0
        var max_id: Int64 = 0
        
        if pullUp {
            max_id = dataArray.last?.id ?? 0
            
            if max_id > 0 {
                max_id = max_id - 1
            }
        } else {
            since_id = dataArray.first?.id ?? 0
        }
        
        WBCacheTool.loadData(since_id: since_id, max_id: max_id, success: { (isCache, response) in
            self.refreshView.endRefreshing()
            self.ActIndicator.stopAnimating()
            
            var array: [WBFristPageDataModel] = [WBFristPageDataModel]()
            
            for dic in response as! [[String : AnyObject]] {
                array.append(WBFristPageDataModel(dic: dic))
            }
            
            if pullUp {
                self.dataArray = self.dataArray + array
            } else {
                self.dataArray = array + self.dataArray
                if !isCache {
                    self.showPromptLabel(array.count)
                }
            }
            
            self.tableView.reloadData()
            }) { (error) in
                print("error:\(error)")
        }
    }
    
}

extension WBHomeTableViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! WBFristPageTableViewCell
        
        cell.dataModel = dataArray[indexPath.row]
        
        return cell
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == (dataArray.count - 1) && (!ActIndicator.isAnimating()) {
            ActIndicator.startAnimating()
            loadData(pullUp: ActIndicator.isAnimating())
        }
    }

}
